/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.kill;

import cn.ac.iie.di.util.GlobalParas;
import cn.ac.iie.di.rocketmq.RocketMqClient;
import org.apache.log4j.Logger;
import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
 *
 *
 */
public class KillHandler implements SignalHandler {

    public static Logger log = Logger.getLogger(KillHandler.class.getName());

    public KillHandler() {
    }

    public void registerSignal(String signalName) {
        Signal signal = new Signal(signalName);
        Signal.handle(signal, this);
    }

    @Override
    public void handle(Signal signal) {
        log.info("now receive the system signal " + signal.getName() + " " + signal.getNumber() + "\n\n");
        if (signal.getName().equals("TERM")) {
            log.info("shutting the rockert consumer ... ");
            log.info("GlobalParas.RocketmqclientQueue size is : " + GlobalParas.rocketmqclientQueue.size());
            try {
                while (!GlobalParas.rocketmqclientQueue.isEmpty()) {
                    RocketMqClient rmc = GlobalParas.rocketmqclientQueue.poll();
                    rmc.shutDownConsumer();
                    log.info("kill a pull thread ");
                    GlobalParas.isShouldExit = true;
                }
                log.info("GlobalParas.RocketmqclientQueue size is : ********" + GlobalParas.rocketmqclientQueue.size());

                while (true) {
                    log.info("GlobalParas.oriMsgPool available size is : " + GlobalParas.oriMsgPool.size());
                    Thread.sleep(1000);
                    if (GlobalParas.oriMsgPool.isEmpty() && GlobalParas.isShouldExit) {
                        GlobalParas.spm.stop();
                        log.info("GlobalParas.spm.stop OK");
                        break;
                    }
                }
            } catch (InterruptedException ex) {
                log.error(ex.getMessage(), ex);
            }catch(Exception ex){
                log.error(ex.getMessage(), ex);
            }
        } else {
            log.info("can not process the system signal " + signal.toString());
        }
        log.info("stop OK");
    }
}
